<template>
    <div class="product-preview">
        <div class="preview-title">
            <i class="el-icon-view"></i>
            <span>商品预览</span>
        </div>

        <div class="preview-card">
            <div class="preview-image">
                <img v-if="previewImage" :src="previewImage" alt="商品主图">
                <div v-else class="empty-image">
                    <i class="el-icon-picture"></i>
                    <p>暂无图片</p>
                </div>
            </div>

            <div class="preview-body">
                <div class="product-name">{{ spuForm.name || '商品名称' }}</div>

                <div class="price-section">
                    <div class="price">¥{{ formatPrice(selectedSku ? selectedSku.price : 0) }}</div>
                    <div class="market-price" v-if="selectedSku && selectedSku.market_price > 0">
                        ¥{{ formatPrice(selectedSku.market_price) }}
                    </div>
                </div>

                <div class="tags-section" v-if="tags.length > 0">
                    <div v-for="tag in tags" :key="tag.id" class="tag" :style="getTagStyle(tag)">
                        {{ tag.name }}
                    </div>
                </div>

                <div class="promotion-section" v-if="promotions.length > 0">
                    <div class="section-label">促销</div>
                    <div v-for="promo in promotions" :key="promo.id" class="promotion-item">
                        <span class="promotion-tag">{{ promo.type === 1 ? '折扣' : promo.type === 5 ? '满减' : '促销'
                            }}</span>
                        <span class="promotion-name">{{ promo.name }}</span>
                    </div>
                </div>

                <div class="spec-section" v-if="Object.keys(specGroups).length > 0">
                    <div class="section-label">选择规格</div>
                    <div class="spec-groups">
                        <div v-for="(values, name) in specGroups" :key="name" class="spec-group">
                            <div class="spec-name">{{ name }}</div>
                            <div class="spec-values">
                                <div v-for="value in values" :key="value" class="spec-value"
                                    :class="{ active: isSpecSelected(name, value) }" @click="selectSpec(name, value)">
                                    {{ value }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="quantity-section">
                    <div class="section-label">数量</div>
                    <div class="quantity-control">
                        <el-input-number v-model="quantity" :min="1" :max="selectedSku ? selectedSku.stock : 999"
                            size="small"></el-input-number>
                        <span class="stock-info" v-if="selectedSku">
                            库存: {{ selectedSku.stock }}
                        </span>
                    </div>
                </div>

                <div class="service-section" v-if="spuForm.services && spuForm.services.length > 0">
                    <div class="section-label">服务</div>
                    <div class="service-tags">
                        <div v-for="service in spuForm.services" :key="service" class="service-tag">
                            <i class="el-icon-check"></i>
                            <span>{{ service }}</span>
                        </div>
                    </div>
                </div>

                <div class="action-section">
                    <el-button type="danger" size="small" icon="el-icon-shopping-cart-2">
                        加入购物车
                    </el-button>
                    <el-button type="warning" size="small" icon="el-icon-shopping-bag-1">
                        立即购买
                    </el-button>
                </div>
            </div>
        </div>

        <div class="preview-tabs">
            <div class="tab active">商品详情</div>
            <div class="tab">规格参数</div>
            <div class="tab">用户评价</div>
        </div>

        <div class="preview-detail">
            <div class="detail-content">
                <div v-if="spuForm.detail" v-html="spuForm.detail"></div>
                <div v-else class="empty-detail">
                    <i class="el-icon-document"></i>
                    <p>暂无详情</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'ProductPreview',
    props: {
        spuForm: {
            type: Object,
            required: true
        },
        skuList: {
            type: Array,
            default: () => []
        },
        marketingForm: {
            type: Object,
            default: () => ({})
        },
        tagOptions: {
            type: Array,
            default: () => []
        },
        promotionOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            selectedSpecs: {},
            quantity: 1,
            imageCache: {},
            isDestroyed: false
        };
    },
    computed: {
        previewImage() {
            if (this.spuForm.main_image_list && this.spuForm.main_image_list.length > 0) {
                const file = this.spuForm.main_image_list[0];
                if (file.url) {
                    return file.url;
                } else if (file.raw) {
                    return this.createObjectURL(file);
                }
            }
            return '';
        },

        tags() {
            if (!this.marketingForm.tags || !this.tagOptions) {
                return [];
            }

            return this.tagOptions.filter(tag =>
                this.marketingForm.tags.includes(tag.id)
            );
        },

        specGroups() {
            const groups = {};

            if (!this.skuList || this.skuList.length === 0) {
                return groups;
            }

            const limitedSkuList = this.skuList.slice(0, 10);
            limitedSkuList.forEach(sku => {
                if (sku.spec_data) {
                    Object.keys(sku.spec_data).forEach(specName => {
                        if (!groups[specName]) {
                            groups[specName] = new Set();
                        }
                        groups[specName].add(sku.spec_data[specName]);
                    });
                }
            });

            const result = {};
            Object.keys(groups).forEach(specName => {
                result[specName] = Array.from(groups[specName]);
            });

            return result;
        },

        selectedSku() {
            if (!this.skuList || this.skuList.length === 0) {
                return null;
            }

            const selectedSpecsCount = Object.keys(this.selectedSpecs).length;
            const specGroupsCount = Object.keys(this.specGroups).length;

            if (selectedSpecsCount < specGroupsCount) {
                return null;
            }

            return this.skuList.find(sku => {
                if (!sku.spec_data) {
                    return false;
                }

                for (const specName in this.selectedSpecs) {
                    if (sku.spec_data[specName] !== this.selectedSpecs[specName]) {
                        return false;
                    }
                }

                return true;
            });
        },

        promotions() {
            if (!this.marketingForm.promotions || !this.promotionOptions) {
                return [];
            }

            return this.promotionOptions.filter(promo =>
                this.marketingForm.promotions.includes(promo.id)
            ).slice(0, 3);
        }
    },
    methods: {
        formatPrice(price) {
            return parseFloat(price).toFixed(2);
        },

        getTagStyle(tag) {
            if (tag.style_config && tag.style_config.color) {
                return {
                    backgroundColor: `${tag.style_config.color}20`,
                    color: tag.style_config.color,
                    borderColor: `${tag.style_config.color}50`
                };
            }
            return {};
        },

        isSpecSelected(specName, value) {
            return this.selectedSpecs[specName] === value;
        },

        selectSpec(specName, value) {
            this.$set(this.selectedSpecs, specName, value);
        },

        releaseImageResources() {
            Object.values(this.imageCache).forEach(url => {
                try {
                    URL.revokeObjectURL(url);
                } catch (e) {
                    // 忽略错误
                }
            });
            this.imageCache = {};
        },

        createObjectURL(file) {
            if (this.isDestroyed) {
                return '';
            }

            const fileId = file.uid || Math.random().toString(36).substring(2);
            if (!this.imageCache[fileId]) {
                this.imageCache[fileId] = URL.createObjectURL(file.raw);
            }
            return this.imageCache[fileId];
        }
    },
    mounted() {
        this.isDestroyed = false;
    },
    beforeDestroy() {
        this.isDestroyed = true;
        this.releaseImageResources();
    },
    watch: {
        skuList: {
            handler(newVal) {
                if (newVal && newVal.length > 0 && newVal[0].spec_data) {
                    this.selectedSpecs = { ...newVal[0].spec_data };
                }
            },
            deep: true
        }
    }
};
</script>

<style scoped>
.product-preview {
    padding: 15px;
}

.preview-title {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.preview-title i {
    margin-right: 8px;
    color: #409EFF;
}

.preview-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 15px;
}

.preview-image {
    height: 200px;
    background: #f5f5f5;
    position: relative;
    overflow: hidden;
}

.preview-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.empty-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #bbb;
}

.empty-image i {
    font-size: 40px;
    margin-bottom: 10px;
}

.preview-body {
    padding: 15px;
}

.product-name {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
    line-height: 1.4;
}

.price-section {
    display: flex;
    align-items: baseline;
    margin-bottom: 12px;
}

.price {
    font-size: 20px;
    font-weight: 700;
    color: #f56c6c;
}

.market-price {
    font-size: 14px;
    color: #999;
    text-decoration: line-through;
    margin-left: 8px;
}

.tags-section {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 12px;
}

.tag {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    background: #f0f0f0;
    border: 1px solid #e0e0e0;
}

.section-label {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #555;
}

.spec-section {
    margin-bottom: 15px;
}

.spec-group {
    margin-bottom: 10px;
}

.spec-name {
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
}

.spec-values {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.spec-value {
    padding: 4px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.spec-value:hover {
    border-color: #409EFF;
}

.spec-value.active {
    border-color: #409EFF;
    background-color: #ecf5ff;
    color: #409EFF;
}

.quantity-section {
    margin-bottom: 15px;
}

.quantity-control {
    display: flex;
    align-items: center;
}

.stock-info {
    margin-left: 10px;
    font-size: 12px;
    color: #999;
}

.service-section {
    margin-bottom: 15px;
}

.service-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.service-tag {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #666;
}

.service-tag i {
    color: #67c23a;
    margin-right: 4px;
}

.action-section {
    display: flex;
    gap: 10px;
    margin-top: 15px;
}

.preview-tabs {
    display: flex;
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
}

.tab {
    padding: 8px 15px;
    font-size: 14px;
    cursor: pointer;
    position: relative;
}

.tab.active {
    color: #409EFF;
    font-weight: 600;
}

.tab.active:after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background: #409EFF;
}

.preview-detail {
    min-height: 100px;
    padding: 10px 0;
}

.empty-detail {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    color: #bbb;
}

.empty-detail i {
    font-size: 30px;
    margin-bottom: 10px;
}

.promotion-section {
    margin-bottom: 12px;
}

.promotion-item {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
    font-size: 12px;
}

.promotion-tag {
    padding: 1px 4px;
    background-color: #ff6b00;
    color: white;
    border-radius: 2px;
    margin-right: 5px;
}

.promotion-name {
    color: #666;
}
</style>